//
//  XHComposeViewController.swift
//  gu-新浪微博
//
//  Created by xiaohui on 16/7/3.
//  Copyright © 2016年 gusheghui. All rights reserved.
//

import UIKit


class XHComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
        setupUI()
    }

    func setupUI(){

        view.addSubview(composeTextView)
        view.addSubview(composeTabarView)
        view.addSubview(pictrueView)
        
        setupNav()
        composeTabarView.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(view)
            make.height.equalTo(44)
        }
        pictrueView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(composeTextView).offset(10)
            make.top.equalTo(composeTextView).offset(240)
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))

        }
        
        //实现点击加号的闭包
        pictrueView.showPicClosure = {[weak self] ()->() in
            self?.selectImage()
        }
        
        composeTabarView.closure = {[weak self](type: XHComposeTabarType) ->() in
            switch type{
            case .pictureButton:
                self?.selectImage()
            case .mentionButton:
                print("2")
            case .trendButton:
                print("3")
            case .emoticonButton:
                print("4")
            case .addButton:
                print("5")
         
            }
        }
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    // 监听键盘frame改变
    func keyboardWillChangeFrame(noti: NSNotification){
        // NSRect mac开发中用得 我们移动端开发CGRect 需要我们先把NSRect 转成NSValue
        // 如果rect
        let rect = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        // 更新toolbar 约束
        composeTabarView.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(rect.origin.y - SCREENH)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            // 更新布局
            self.view.layoutIfNeeded()
        }
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "leftBarButtonClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "rightBarButtonClick")
        composeTextView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        navigationItem.rightBarButtonItem?.enabled = false
        //设置中间title
        navigationItem.titleView = centerLable
        
    }
    //取消按钮点击事件
    @objc func leftBarButtonClick(){
        composeTextView.resignFirstResponder()
        dismissViewControllerAnimated(false, completion: nil)
    }
    //发送按钮点击事件
    @objc func rightBarButtonClick(){
//        print("fasong")
        update()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //懒加载控件 设置中间label文字
    private lazy var centerLable : UILabel = {
        let name = XHUserAccountTools.sharedTools.userAccount?.screen_name ?? ""
        let str = "发微博\n\(name)"
        
        //富文本  获取range
        //转成oc  并截取
        let range = (str as NSString).rangeOfString(name)
        
        //设置属性 字体颜色和大小
        let attr = NSMutableAttributedString(string: str)
        attr.addAttributes([NSForegroundColorAttributeName:ThemeColor,NSFontAttributeName:UIFont.systemFontOfSize(13)], range: range)
        let lable = UILabel()
        lable.attributedText = attr
        lable.textAlignment = .Center
        lable.numberOfLines = 0
        //中间navigationItem.titleView 系统默认有一个fream
        lable.sizeToFit()
        
        return lable
    }()
    
    private lazy var composeTabarView :XHComposeTabar = XHComposeTabar()
    
    private lazy var composeTextView:XHComposeTextView = {
       
        let textView = XHComposeTextView()
        textView.delegate = self
        textView.alwaysBounceVertical = true
        
        textView.font = UIFont.systemFontOfSize(50)
        
        textView.placeholderStr = "cao  ni  mei"
        
        return textView
    }()
    
    private lazy var pictrueView:XHComposePictureView = XHComposePictureView()
}

extension XHComposeViewController:UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
//        print("编辑")
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
//        print("移动")
        //移动的时候隐藏键盘
        composeTextView.resignFirstResponder()
    }
}

extension XHComposeViewController{
    func update(){
        XHNetworkTools.sharedTools.composeUpdate(composeTextView.text, success: { (response) -> () in
            print("发送成功")
            }) { (error) -> () in
                print("发送失败")
        }

    }
}

extension XHComposeViewController{
    func selectImage(){
        let picker = UIImagePickerController()
        picker.delegate = self
        presentViewController(picker, animated: true, completion: nil)
        
    }
}
extension XHComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        composeTextView.backgroundColor = UIColor(patternImage: image)
        picker.dismissViewControllerAnimated(false, completion: nil)
        
        pictrueView.addImages(image)
    }
}

